<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>语音聊天调试测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 600px;
            margin: 20px auto;
            padding: 20px;
        }
        button {
            margin: 10px 5px;
            padding: 10px 20px;
            font-size: 16px;
        }
        .result {
            margin: 10px 0;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            white-space: pre-wrap;
            max-height: 300px;
            overflow-y: auto;
        }
        .success { background: #d4edda; }
        .error { background: #f8d7da; }
        input { width: 300px; padding: 8px; margin: 5px; }
    </style>
</head>
<body>
    <h1>🔧 语音聊天调试测试</h1>
    
    <div>
        <h3>1. 后端连接测试</h3>
        <button onclick="testBackend()">测试后端连接</button>
        <div id="backendResult" class="result"></div>
    </div>
    
    <div>
        <h3>2. 文本聊天测试</h3>
        <input type="text" id="textInput" placeholder="输入测试文本" value="你好" />
        <button onclick="testTextChat()">测试文本聊天</button>
        <div id="textResult" class="result"></div>
    </div>
    
    <div>
        <h3>3. WebSocket连接测试</h3>
        <button onclick="testWebSocket()">测试WebSocket</button>
        <div id="wsResult" class="result"></div>
    </div>
    
    <div>
        <h3>4. 录音功能测试</h3>
        <button id="recordBtn" onclick="toggleRecording()">开始录音</button>
        <span id="recordTime"></span>
        <div id="recordResult" class="result"></div>
    </div>

    <script>
        const API_BASE = 'http://localhost:8123/api';
        const WS_URL = 'ws://localhost:8123/ws/voice-chat';
        
        let ws = null;
        let mediaRecorder = null;
        let audioChunks = [];
        let isRecording = false;
        let recordStartTime = 0;

        // 测试后端连接
        async function testBackend() {
            const result = document.getElementById('backendResult');
            result.textContent = '测试中...';
            result.className = 'result';
            
            try {
                // 测试健康检查
                const healthResponse = await fetch(`${API_BASE}/chat/health`);
                const healthText = await healthResponse.text();
                
                result.textContent = `✅ 后端服务正常\n健康检查: ${healthText}`;
                result.className = 'result success';
            } catch (error) {
                result.textContent = `❌ 后端连接失败: ${error.message}`;
                result.className = 'result error';
            }
        }

        // 测试文本聊天
        async function testTextChat() {
            const input = document.getElementById('textInput');
            const result = document.getElementById('textResult');
            
            if (!input.value.trim()) {
                alert('请输入测试文本');
                return;
            }
            
            result.textContent = '处理中...';
            result.className = 'result';
            
            try {
                const response = await fetch(`${API_BASE}/chat/voice`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        textInput: input.value,
                        sessionId: 'debug-test-' + Date.now()
                    })
                });
                
                const data = await response.json();
                
                if (data.status === 'success') {
                    result.textContent = `✅ 文本聊天成功
识别文本: ${data.recognizedText}
AI回复: ${data.aiResponse}
处理时间: ${data.processingTime}ms
会话ID: ${data.sessionId}`;
                    result.className = 'result success';
                    
                    // 播放音频
                    if (data.audioBase64) {
                        playAudio(data.audioBase64);
                    }
                } else {
                    result.textContent = `❌ 文本聊天失败: ${data.errorMessage}`;
                    result.className = 'result error';
                }
            } catch (error) {
                result.textContent = `❌ 请求失败: ${error.message}`;
                result.className = 'result error';
            }
        }

        // 测试WebSocket
        function testWebSocket() {
            const result = document.getElementById('wsResult');
            
            if (ws && ws.readyState === WebSocket.OPEN) {
                ws.close();
                return;
            }
            
            result.textContent = 'WebSocket连接中...';
            result.className = 'result';
            
            try {
                ws = new WebSocket(WS_URL);
                
                ws.onopen = () => {
                    result.textContent = '✅ WebSocket连接成功\n';
                    result.className = 'result success';
                    
                    // 发送测试消息
                    const testMessage = {
                        textInput: 'WebSocket测试消息',
                        sessionId: 'ws-debug-test-' + Date.now()
                    };
                    ws.send(JSON.stringify(testMessage));
                    result.textContent += '📤 已发送测试消息\n';
                };
                
                ws.onmessage = (event) => {
                    try {
                        const data = JSON.parse(event.data);
                        result.textContent += `📥 收到消息: ${JSON.stringify(data, null, 2)}\n`;
                        
                        if (data.type === 'voice-response' && data.data) {
                            const responseData = data.data;
                            if (responseData.audioBase64) {
                                playAudio(responseData.audioBase64);
                            }
                        }
                    } catch (error) {
                        result.textContent += `❌ 消息解析失败: ${error.message}\n`;
                    }
                };
                
                ws.onclose = () => {
                    result.textContent += '🔌 WebSocket连接已关闭\n';
                };
                
                ws.onerror = (error) => {
                    result.textContent = `❌ WebSocket错误: ${error}\n`;
                    result.className = 'result error';
                };
            } catch (error) {
                result.textContent = `❌ WebSocket创建失败: ${error.message}`;
                result.className = 'result error';
            }
        }

        // 录音功能
        async function toggleRecording() {
            if (isRecording) {
                stopRecording();
            } else {
                await startRecording();
            }
        }

        async function startRecording() {
            const result = document.getElementById('recordResult');
            const btn = document.getElementById('recordBtn');
            
            try {
                const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
                mediaRecorder = new MediaRecorder(stream);
                audioChunks = [];
                
                mediaRecorder.ondataavailable = (event) => {
                    audioChunks.push(event.data);
                };
                
                mediaRecorder.onstop = async () => {
                    const audioBlob = new Blob(audioChunks, { type: 'audio/webm' });
                    
                    // 转换为Base64
                    const reader = new FileReader();
                    reader.onload = async () => {
                        const base64Data = reader.result.split(',')[1];
                        
                        result.textContent += '\n🎯 正在测试语音识别...';
                        
                        try {
                            const response = await fetch(`${API_BASE}/chat/voice`, {
                                method: 'POST',
                                headers: { 'Content-Type': 'application/json' },
                                body: JSON.stringify({
                                    audioBase64: base64Data,
                                    sessionId: 'voice-debug-test-' + Date.now()
                                })
                            });
                            
                            const data = await response.json();
                            
                            if (data.status === 'success') {
                                result.textContent += `\n✅ 语音识别成功！
识别文本: ${data.recognizedText}
AI回复: ${data.aiResponse}
处理时间: ${data.processingTime}ms`;
                                result.className = 'result success';
                                
                                if (data.audioBase64) {
                                    playAudio(data.audioBase64);
                                }
                            } else {
                                result.textContent += `\n❌ 语音识别失败: ${data.errorMessage}`;
                                result.className = 'result error';
                            }
                        } catch (error) {
                            result.textContent += `\n❌ 语音识别请求失败: ${error.message}`;
                            result.className = 'result error';
                        }
                    };
                    reader.readAsDataURL(audioBlob);
                    
                    // 停止音轨
                    stream.getTracks().forEach(track => track.stop());
                };
                
                mediaRecorder.start();
                isRecording = true;
                recordStartTime = Date.now();
                
                btn.textContent = '停止录音';
                result.textContent = '🎤 正在录音...';
                result.className = 'result';
                
                // 更新录音时间
                const timer = setInterval(() => {
                    if (isRecording) {
                        const elapsed = Math.floor((Date.now() - recordStartTime) / 1000);
                        document.getElementById('recordTime').textContent = `${elapsed}s`;
                    } else {
                        clearInterval(timer);
                    }
                }, 1000);
                
            } catch (error) {
                result.textContent = `❌ 录音启动失败: ${error.message}`;
                result.className = 'result error';
            }
        }

        function stopRecording() {
            if (mediaRecorder && isRecording) {
                mediaRecorder.stop();
                isRecording = false;
                
                document.getElementById('recordBtn').textContent = '开始录音';
                document.getElementById('recordTime').textContent = '';
            }
        }

        // 播放音频
        function playAudio(base64Data) {
            try {
                const binaryString = atob(base64Data);
                const bytes = new Uint8Array(binaryString.length);
                for (let i = 0; i < binaryString.length; i++) {
                    bytes[i] = binaryString.charCodeAt(i);
                }
                const blob = new Blob([bytes], { type: 'audio/webm' });
                const url = URL.createObjectURL(blob);
                const audio = new Audio(url);
                audio.play().catch(e => console.log('音频播放失败:', e));
            } catch (error) {
                console.error('音频播放处理失败:', error);
            }
        }

        // 页面加载时测试后端
        window.addEventListener('load', testBackend);
    </script>
</body>
</html>
